function [Eqtn, MaxSh, MinSh, lsInvalid] = evaltimesubs(Eqtn)
% evaltimesubs  [Not a public function] Validate and evaluate time subscripts.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2015 IRIS Solutions Team.

%--------------------------------------------------------------------------

MaxSh = 0;
MinSh = 0;
lsInvalid = cell(1,0);

Eqtn = strrep(Eqtn,'{t+','{+');
Eqtn = strrep(Eqtn,'{t-','{-');
Eqtn = strrep(Eqtn,'{0}','');
Eqtn = strrep(Eqtn,'{-0}','');
Eqtn = strrep(Eqtn,'{+0}','');

% Replace standard time subscripts {k} with {@+k}.
Eqtn = regexprep(Eqtn,'\{(\d+)\}','{@+$1}');
% Replace standard time subscripts {+k} or {-k} with {@+k} or {@-k}.
Eqtn = regexprep(Eqtn,'\{([\+\-]\d+)\}','{@$1}');

% Find nonstandard time subscripts, try to evaluate them and replace with
% a standard string
ptn = '\{[^@].*?\}';
[from, to] = regexp(Eqtn, ptn, 'start', 'end');
for iEqtn = 1 : length(from)
    for j = length( from{iEqtn} ) : -1 : 1
        c = Eqtn{iEqtn}( from{iEqtn}(j):to{iEqtn}(j) );
        evalNonstandardTimeSubs( );
        Eqtn{iEqtn} = [ ...
            Eqtn{iEqtn}( 1:from{iEqtn}(j)-1 ), ...
            c, ...
            Eqtn{iEqtn}( to{iEqtn}(j)+1:end ), ...
            ];
    end
end

% Find max and min time shifts.
c = regexp(Eqtn,'\{@[+\-]\d+\}','match');
c = [c{:}]; % Expand individual equations.
c = [c{:}]; % Expand matches into one string.
if ~isempty(c)
    x = sscanf(c,'{@%g}');
    x = [0;x(:)].';
    MaxSh = max(x);
    MinSh = min(x);
end

return




    function evalNonstandardTimeSubs()
        try
            % Use protected eval to avoid conflict with workspace.
            xx = protectedEval( c(2:end-1) );
            if isintscalar(xx)
                xx = round(xx);
                if xx==0
                    c = '';
                    return
                else
                    c = sprintf('{@%+g}',xx);
                    return
                end
            end
        catch
            lsInvalid{end+1} = c;
            c = '';
            return
        end
    end
end




function varargout = protectedEval(varargin)
varargout{1} = eval(varargin{1});
end
